package com.zhouzi.zhaoyang.ui.activity

import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.KeyEvent
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.AuthCodeBean
import com.zhouzi.zhaoyang.bean.OrderDetailBean
import com.zhouzi.zhaoyang.config.JobFinal
import com.zhouzi.zhaoyang.mvp.p.CashActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.ICashActivityView
import com.zhouzi.zhaoyang.service.PrintService
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.Calculator
import com.zhouzi.zhaoyang.util.FaceUtil
import com.zhouzi.zhaoyang.util.MyHttp
import kotlinx.android.synthetic.main.cash_pledge_activity.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class CashPledgeActivity : BaseActivity(), ICashActivityView {
    override fun errorToken() {
        exitToLogin()
    }


    var deviceNo = Build.SERIAL
    override fun getAuthCodeSuccess(data: AuthCodeBean?) {
        data?.let {
            val map = mutableMapOf(
                Pair("appid", it.appid),
                Pair("mch_id", it.mchId),
                Pair("store_id", it.storeId),
                Pair("out_trade_no", it.outTradeNo),
                Pair("face_authtype", "FACEPAY"),
                Pair("authinfo", it.authinfo),
                Pair("ask_face_permit", "1"),
                Pair("total_fee", money),
                Pair("sub_appid", it.subAppId),
                Pair("sub_mch_id", it.subMchId),
                Pair("face_code_type", "1"),
                Pair("ask_ret_page", "1")//是否展示微信支付成功页，可选值："0"，不展示；"1"，展示
            )

            WxPayFace.getInstance().getWxpayfaceCode(map, object : IWxPayfaceCallback() {
                override fun response(p0: MutableMap<Any?, Any?>?) {
                    Handler(Looper.getMainLooper()).post {
                        if (FaceUtil().isSuccessInfo(p0)) {
                            if (cashPledge.toDouble() > 0) {
                                val requestMap = mutableMapOf(
                                    Pair("faceCode", p0?.get("face_code") as String),
                                    Pair("deviceNo", deviceNo),
                                    Pair("consumeFee", yuan.toString()),
                                    Pair("depositFee", cash.toString()),
                                    Pair("outTradeNo", data.outTradeNo),
                                    Pair("subOpenId", p0?.get("openid") as String)
//                                            Pair("subOpenId", p0?.get("sub_openid") as String)



                                )
                                Log.e("openid",p0.toString())
                                p.payDepositorder(requestMap, data)
                            }

                        } else {
                            Toast.makeText(mContext, "获取faceCode失败，请稍后再试", Toast.LENGTH_SHORT)
                                .show()
                        }
                    }
                }
            })

        }

    }

    override fun getAuthCodeFailed(msg: String) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }

    override fun getOrderSuccess(orderDetail: OrderDetailBean?) {
        orderDetail?.let {
            printProductInformation(orderDetail)
            MyHttp.report(orderDetail)
            Calculator.reset()

        }

    }

    private fun getUsbDeviceList(): MutableList<UsbDevice> {
        val usbDevices = mutableListOf<UsbDevice>()
        val usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        val devices = usbManager.deviceList
        val deviceIterator = devices.values.iterator()
        if (devices.size > 0) {
            while (deviceIterator.hasNext()) {
                val usbDevice = deviceIterator.next()
                if (checkUsbDevicePidVid(usbDevice))
                    usbDevices.add(usbDevice)
            }
        }
        return usbDevices
    }

    private fun checkUsbDevicePidVid(dev: UsbDevice): Boolean {
        val pid = dev.productId
        val vid = dev.vendorId
        return (vid == 34918 && pid == 256 || vid == 1137 && pid == 85
                || vid == 6790 && pid == 30084
                || vid == 26728 && pid == 256 || vid == 26728 && pid == 512
                || vid == 26728 && pid == 256 || vid == 26728 && pid == 768
                || vid == 26728 && pid == 1024 || vid == 26728 && pid == 1280
                || vid == 26728 && pid == 1536)
    }

    override fun getOrderFailed(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT)
    }

    override fun payDepositorderSuccess(authCodeBean: AuthCodeBean) {

        val map = mutableMapOf(
            Pair("appid", authCodeBean.appid),
            Pair("mch_id", authCodeBean.mchId),
            Pair("store_id", authCodeBean.storeId),
            Pair("authinfo", authCodeBean.authinfo),
            Pair("payresult", "SUCCESS")
        )

        WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {

                var activity = Intent(mContext, MainActivity::class.java)
                startActivity(activity)
                finish()

            }
        })

        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "交易成功")
        startService(intent)



        p.getOrder(authCodeBean.outTradeNo)


    }

    override fun payDepositorderFailed(authCodeBean: AuthCodeBean) {

        val map = mutableMapOf(
            Pair("appid", authCodeBean.appid),
            Pair("mch_id", authCodeBean.mchId),
            Pair("store_id", authCodeBean.storeId),
            Pair("authinfo", authCodeBean.authinfo),
            Pair("payresult", "ERROR")
        )
        WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
               finish()
            }
        })

        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "交易失败")
        startService(intent)
    }


    override fun showLoadDialog() {
        loadDialog.show()
    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()

    }


    override fun getLayoutId(): Int {
        return R.layout.cash_pledge_activity
    }

    private val p = CashActivityPresenter()

    init {
        p.attachView(this)
    }


    override fun onDestroy() {
        super.onDestroy()
        p.detachView()

    }


    var enter = 160
    var money = "0"
    var cashPledge = "0"
    var yuan = 0L
    var cash = 0L
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {

        Calculator.onKeyEvent(
            when (event?.keyCode) {
                KeyEvent.KEYCODE_NUMPAD_1 -> Calculator.KeyCode._1
                KeyEvent.KEYCODE_NUMPAD_2 -> Calculator.KeyCode._2
                KeyEvent.KEYCODE_NUMPAD_3 -> Calculator.KeyCode._3
                KeyEvent.KEYCODE_NUMPAD_4 -> Calculator.KeyCode._4
                KeyEvent.KEYCODE_NUMPAD_5 -> Calculator.KeyCode._5
                KeyEvent.KEYCODE_NUMPAD_6 -> Calculator.KeyCode._6
                KeyEvent.KEYCODE_NUMPAD_7 -> Calculator.KeyCode._7
                KeyEvent.KEYCODE_NUMPAD_8 -> Calculator.KeyCode._8
                KeyEvent.KEYCODE_NUMPAD_9 -> Calculator.KeyCode._9
                KeyEvent.KEYCODE_NUMPAD_0 -> Calculator.KeyCode._0
                KeyEvent.KEYCODE_NUMPAD_DOT -> Calculator.KeyCode._D
                KeyEvent.KEYCODE_DEL -> Calculator.KeyCode._B
                KeyEvent.KEYCODE_ENTER -> Calculator.KeyCode._E
                else -> return super.onKeyDown(event!!.keyCode, event)
            }
        )


        if ((event?.keyCode == KeyEvent.KEYCODE_ENTER || event?.keyCode == enter)) {

            if (event.getAction() != KeyEvent.ACTION_UP) {
                money = tvMoney.text.toString()
                cashPledge = tvMoney2.text.toString()
                if (money.equals("") || money.toDouble() <= 0) {
                    val serviceIntent = Intent(mContext, VoiceService::class.java)
                    serviceIntent.putExtra("voiceStr", "请输入房费")
                    startService(serviceIntent)
                    tvMoney.requestFocus()
                    return false
                } else if (cashPledge.equals("") || cashPledge.toDouble() <= 0) {
                    val serviceIntent = Intent(mContext, VoiceService::class.java)
                    serviceIntent.putExtra("voiceStr", "请输入押金")
                    startService(serviceIntent)
                    tvMoney2.requestFocus()
                    return false
                } else {


                    val serviceIntent = Intent(mContext, VoiceService::class.java)
                    serviceIntent.putExtra(
                        "voiceStr",
                        "消费" + money + "元," + "押金" + cashPledge + "元"
                    )
                    startService(serviceIntent)


                    if (money?.toDouble() > 0 && cashPledge?.toDouble() > 0) {

                        yuan = Calculator.yuan2Fen(money)
                        cash = Calculator.yuan2Fen(cashPledge)
                        face(this, Build.SERIAL, p)

                    }

                    return false
                }
            } else {
                return false
            }
        } else {
            return super.dispatchKeyEvent(event)
        }


    }


    override fun initView() {
        tvApBtn.setOnClickListener {


            val intent = Intent(mContext, MainActivity::class.java)
            startActivity(intent)
            Calculator.reset()
            finish()


        }
    }

    private var job: Job? = null
    private fun countDown() {
        /*开始倒计时30s退出页面*/
        job = GlobalScope.launch {
            delay(JobFinal.EXECUTE_TIME)
            val intent = Intent(mContext, VoiceService::class.java)
            intent.putExtra("voiceStr", "交易失败")
            startService(intent)
            var activity = Intent(mContext,MainActivity :: class.java)
            startActivity(activity)
            finish()
        }
    }



    override fun onResume() {
        super.onResume()
        //执行1分钟倒计时，返回主界面
        countDown()
//        tvMoney.text = ""
//        tvMoney2.text = ""
        tvMoney.requestFocus()
        val serviceIntent = Intent(mContext, VoiceService::class.java)
        serviceIntent.putExtra("voiceStr", "请输入房费")
        startService(serviceIntent)
    }


    override fun onPause() {
        super.onPause()
        job?.cancel()
    }

    fun face(mContext: Context, deviceNo: String, p: CashActivityPresenter) {

        /*初始化刷脸*/
        WxPayFace.getInstance().initWxpayface(mContext, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (isSuccessInfo(p0)) {
                        getRawData(mContext, deviceNo, p)
                    } else {
                        Toast.makeText(mContext, "初始化失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })


    }


    public fun printProductInformation(orderDetail: OrderDetailBean) {
        App.instance().initPrinter()
        val devices = getUsbDeviceList()
        if (devices.size == 0) {
            return
        }
        val deviceNames = devices.map {
            it.deviceName
        }
        MaterialDialog.Builder(mContext)
            .items(deviceNames)
            .itemsCallback { dialog, itemView, position, text ->
                val intent = Intent(mContext, PrintService::class.java)
                intent.putExtra("status", PrintService.CONNECT_DEVICE)
                intent.putExtra("usbDevice", devices[position])

                // 实体类
                putEntity(intent, orderDetail)

                startService(intent)
            }.show()


        App.instance().printOrder(orderDetail)

        startService(Intent(mContext, PrintService::class.java))

    }

    private fun putEntity(
        intent: Intent,
        orderDetail: OrderDetailBean
    ) {
        intent.putExtra("storeName", orderDetail.storeName)
        intent.putExtra("realFee", orderDetail.realFee)
    }


    private fun getRawData(mContext: Context, deviceNo: String, p: CashActivityPresenter) {
        /*获取rawData*/
        WxPayFace.getInstance().getWxpayfaceRawdata(object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (isSuccessInfo(p0)) {
                        val rawData = p0?.get("rawdata").toString()
                        val map = mutableMapOf(
                            Pair("deviceNo", deviceNo),
                            Pair("rawdata", rawData)
                        )
                        p.getAuthCode(map)

                    } else {
                        Toast.makeText(mContext, "获取rawData失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }


    /*判断回调是否异常*/
    public fun isSuccessInfo(info: Map<*, *>?): Boolean {

        if (info == null) {
            RuntimeException("调用返回为空").printStackTrace()
            return false
        }
        val code = info["return_code"] as String
        val msg = info["return_msg"] as String
        Log.d("isSuccessInfo", "response | getWxpayfaceRawdata $code | $msg")
        /* info.get("rawdata").toString() == null || code == null ||*/
        if (!code.equals("SUCCESS")) {
            RuntimeException("调用返回非成功信息,return_msg:" + msg + "   ").printStackTrace()
            return false
        }
        return true
    }


}
